// pages/publish/publish.js
var util = require("../../utils/util.js")
const ctx = wx.createCanvasContext('myCanvas')
const app = getApp();
const db = wx.cloud.database()
const _ = db.command
const labelDB=db.collection('labelData')
const collegeDB=db.collection('collegeData')
const publishDB=db.collection('publishData') //公告数据库
// const publishsMessagedb=db.collection('publishsMessage') //留言数据库

var upsuccess = false
var publishText =''
var pAcademyNum = [] //学院序号
var  pLabelNum = [] //标签序号
var publishPicture =[] //照片对应的云路径
var picSuccess =false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userOpenid:app.globalData.userOpenid,
    //发布一条公告所有筛选条件
    Column: ["#寻物#","#找人#","#表白#"],//栏目
    pColumn:0,
    pAcademy:[],//学院
    pLabel:[],//标签
    //pAcademyNum:[],//学院
    // pLabelNum:[],//标签
    // publishText:'',
    showView: false,
    btnSelect:"选择标签",
    temPicture:[], //临时的照片的照片
    // publishPicture:[],//照片对应的云路径
    addpic_hidden:false, //上传图片显示
    txtareaValue:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     //全局变量  直接获取  当然要首先在我的登陆才会有数据
     //发布一条公告肯定需要用户
     console.log(app.globalData)
    //登录后才能发布信息，方便页面所以注释一下
      if(app.globalData.userOpenid == null){
          wx.showToast({
            title: '请先登录',
            icon:"none",
            mask:true,
            duration:5000,
            success(res){
              setTimeout(() => {
                wx.reLaunch({
                  url: '../../pages/mine/mine',
                })
              }, 2000);
            }
          })
      }else{
        let that = this;
        // var TIME = util.formatTime(new Date());
        // console.log(TIME)
        that.setData({
          showView:false,
       })
      }
    
  },

  //点击添加标签按钮
  addLabel:function(res){
    let col = this.data.pColumn
      wx.navigateTo({
        url: '../publish/selectLabel/selectLabel?col='+col,
      })
  },
  //获取选择的学院标签
  getselectedAcademy:function(academyArray){
     let that = this
     console.log("学院序号",academyArray)
     that.setData({
       pAcademy:[],
      //  pAcademyNum:academyArray
     })
     pAcademyNum = academyArray
     collegeDB.where({
            college:"长江大学"
         }
       ).get({
      success:function(res){
        console.log(res)
        let allacademy = res.data[0].allAcademy
        for(var i=0;i<academyArray.length;i++){
          that.data.pAcademy.push(allacademy[Number(academyArray[i])].academy)
        }
        console.log("得到的学院",that.data.pAcademy)
        that.setData({
          pAcademy:that.data.pAcademy
        })
      },fail:function(res){
          wx.showToast({
            title: '系统出错',
            icon:"none"
          })
      }
    })
  },
  getselectedLabel:function(labelArray){
    let that = this
    console.log("标签序号",labelArray)
    this.setData({
      pLabel:[],
      // pLabelNum:labelArray
    })
    pLabelNum = labelArray
    labelDB.where(_.and(
      {
        col:that.data.pColumn //栏目
      },
      {
      labelNum: _.in(labelArray) //标签
      }
    )).get({
      success:function(res){
        console.log(res)
        for(var i=0;i<labelArray.length;i++){
          that.data.pLabel.push(res.data[i].label)
        }
        console.log("得到的标签",that.data.pLabel)
        that.setData({
          pLabel:that.data.pLabel
        })
      },fail:function(res){
        wx.showToast({
          title: '系统出错',
          icon:"none"
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  //获取书写的文字
  getPublishText:function(e){
    console.log("文字：",e.detail.value)
    // this.setData({
    //   publishText:e.detail.value
    // })
    publishText = e.detail.value
  },
  checkImage:function(_imgpath){
    wx.showLoading({
      title: '检测图片中',
    })   
    let that = this
    var _height = 0
    var _width = 0
    var _type = ''
    wx.getImageInfo({
      src:_imgpath,
      success:function(res){
        console.log("原始图片高度",res.height,res.width)
        console.log("原始图片本地路径和类型",res.path,res.type)
        _height = res.height
        _width = res.width
        _type = res.type
        ctx.drawImage(res.path, 0, 0, 200, parseInt(_height / _width * 200)) //按比例对图片进行画图
        ctx.draw(false, function (res) {
        //把画好的图 描下来，写成临时文件
        console.log("画图",res)
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width:200,
            height: parseInt(_height / _width * 200),
            destWidth: 200,
            destHeight: parseInt(_height / _width * 200),
            canvasId:'myCanvas',
            success: function (res1) {
              console.log("文件：",res1.tempFilePath)
              wx.getFileSystemManager().readFile({
                encoding:'base64',
                filePath: res1.tempFilePath,
                success: res => {
                  console.log( res.data.length) 
                  if(res.data.length*2>4*1024*1024){
                    wx.showToast({
                      title: '图片过大',
                      icon:"none"
                    })
                  }else{
                    wx.serviceMarket.invokeService({
                      service: 'wxee446d7507c68b11',
                      api: 'imgSecCheck',
                      data: {
                        "Action": "ImageModeration",
                        "Scenes": ["PORN", "POLITICS", "TERRORISM"],
                        // "ImageUrl": new wx.serviceMarket.CDN({
                        //   type: 'filePath',
                        //   filePath:eachFile.path,
                        // }),
                        "ImageBase64":res.data,
                      },
                      success:function(res){
                        if(res.data.Response.Suggestion == "PASS"){
                          wx.hideLoading()
                          console.log("图片通过")
                          wx.showToast({
                            title: '图片通过',
                            icon:"none"
                          })
                          that.data.temPicture =  that.data.temPicture.concat(_imgpath)
                          if(that.data.temPicture.length>=3){
                            that.setData({
                              addpic_hidden:true
                            })
                          }
                          that.setData({
                            temPicture: that.data.temPicture
                          })
                        }else{
                          wx.hideLoading()
                          wx.showToast({
                            title: '含有违法违规内容',
                            icon:'none'
                          })
                        }      
                      },fail:function(res){
                        console.log("图片审查出错",res)
                        wx.hideLoading()
                        wx.showToast({
                          title: '审查出错，建议剪裁或者换张图片',
                          icon:'none'
                        })
                      }
                    })          
               }
            },fail:function(res){
              wx.showToast({
                title: '出错，建议剪裁或者换张图片',
                icon:"none"
              })
            }
          })
            },fail:function(res){
              wx.showToast({
                title: '出错，请稍后再试',
                icon:"none"
              })
            }
          })
        })
      },fail:function(res){
        wx.showToast({
          title: '出错，请稍后再试',
          icon:"none"
        })
      }
    })
  },
  //添加图片
  addPicture:function(){
    let that = this
    // let publishid = app.globalData.userOpenid+new Date().getTime()
    // console.log(publishid)
    wx.chooseImage({
            count: 3-that.data.temPicture.length, //最多选择三张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                console.log(res)
                var temPicture =  that.data.temPicture
                var tempFiles = res.tempFiles
                  tempFiles.forEach((eachFile,index)=>{
                    console.log("文件",eachFile)
                      if (eachFile && eachFile.size > 1024 * 1024) {
                      wx.showToast({
                        title: '图片不能大于1M',
                        icon:"none"
                      })
                      return;
                    }else{
                      // wx.showLoading({
                      //   title: '检测图片中',
                      // })    
                      that.checkImage(eachFile.path)
                      // Promise.all([that.checkImage(eachFile.path)]).then(() => {                       
                      //   console.log("promiseMethod:",picSuccess)
                      //   if(picSuccess){
                      //     console.log("成功了")
                      //       wx.hideLoading()
                      //       temPicture =  that.data.temPicture.concat(eachFile.path)
                      //       if(temPicture.length>=3){
                      //         that.setData({
                      //           addpic_hidden:true
                      //         })
                      //       }
                      //       that.setData({
                      //         temPicture: temPicture
                      //       })
                      //       picSuccess = false
                      //   }else{
                      //       console.log("没有成功")
                      //       wx.hideLoading()
                      //   }
                      // })

                      // if( that.checkImage(eachFile.path)){
                      //   console.log("成功了")
                      //   wx.hideLoading()
                      //   temPicture =  that.data.temPicture.concat(eachFile.path)
                      //   if(temPicture.length>=3){
                      //     that.setData({
                      //       addpic_hidden:true
                      //     })
                      //   }
                      //   that.setData({
                      //     temPicture: temPicture
                      //   })
                      // }else{
                      //   console.log("没有成功")
                      //   wx.hideLoading()
                      // }
                    
                  }
                  //   if (eachFile && eachFile.size > 1024 * 1024) {
                  //     wx.showToast({
                  //       title: '图片不能大于1M',
                  //       icon:"none"
                  //     })
                  //     return;
                  //   }else{
                  //     wx.showLoading({
                  //       title: '检测图片中',
                  //     })
                  //     wx.getFileSystemManager().readFile({
                  //     encoding:'base64',
                  //     filePath: eachFile.path,
                  //     success: res => {
                  //     wx.cloud.callFunction({
                  //       name: 'checkImg',
                  //       data: {
                  //         img: res.data
                  //       },
                  //       success(res) {
                  //         wx.hideLoading()
                  //         if (res.result.errCode == 87014) {
                  //           console.log(res.result.errCode)
                  //           wx.showToast({
                  //             icon: 'none',
                  //             title: '含有违法违规内容',
                  //           })
                  //         }else if( res.result.errCode == 0) {
                  //           console.log(res.result.errCode)
                  //           temPicture =  that.data.temPicture.concat(eachFile.path)
                  //           if(temPicture.length>=3){
                  //             that.setData({
                  //               addpic_hidden:true
                  //             })
                  //           }
                  //           that.setData({
                  //             temPicture: temPicture
                  //           })
                  //         }else{
                  //           console.log(res.result.errCode)
                  //           wx.showToast({
                  //             title: '图片出错，请重新选择',
                  //             icon:'none'
                  //           })
                  //         }
                  //       },fail(res){
                  //         console.log("错误原因",res,res)
                  //         // if(res.result.errCode==-404012){
                  //         //   console.log(res.result.errCode)
                  //         //   wx.showToast({
                  //         //     title: '处理超时，请重试',
                  //         //   })
                  //         // }
                  //         wx.showToast({
                  //           title: '系统出错',
                  //           icon:'none'
                  //         })
                  //       }
                  //       })
                  //     },fail:res=>{
                  //       wx.showToast({
                  //         title: '系统出错',
                  //         icon:'none'
                  //       })
                  //     }
                  //   })
                  // }
                  })
          
                // var temPicture =  that.data.temPicture.concat(res.tempFilePaths)
                // if(temPicture.length>=3){
                //   that.setData({
                //     addpic_hidden:true
                //   })
                // }
                // that.setData({
                //   temPicture: temPicture
                // })
            }
          })
  },

  

  //删除图片  （点击红叉叉）
  deletePicture:function(e){
    let that = this
    let picid = e.currentTarget.id
    console.log(e.currentTarget.id)
      wx.showModal({
        title: '',
        content: '要删除这张照片吗？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.data.temPicture.splice(that.data.temPicture.findIndex(e => e === picid), 1) 
            that.setData({
              temPicture: that.data.temPicture,
              addpic_hidden:false
            })
            console.log(that.data.temPicture)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
  },

  //上传图片到云存储
  uploadPicture:function(fileUrl,cloudUrl){
    let that = this
    that.data.temPicture.forEach((item,i)=>{      
      wx.cloud.uploadFile({
          cloudPath: String(cloudUrl)+i+'.jpg', // 上传至云端的路径
          filePath: fileUrl[i], // 小程序临时文件路径
          success: res => {
            console.log(res.fileID)
            publishPicture.push(res.fileID)
            upsuccess = true
          },
          fail: res => {
            upsuccess = false
          }
        })
    })
  },
  //点击发布
  clickPublish:function(){
    // new Date().getTime()
    let that = this
    if(publishText==''){
        wx.showToast({
          title: '你还没写公告呢！',
          icon:"none"
        })
    }else{
      wx.cloud.callFunction({
        name: 'checkTxt',
        data: {
          txt: publishText
        },
        success(res) {
          if (res.result.errCode == 87014) {
            console.log(res.result.errCode)
            wx.showToast({
              icon: 'none',
              title: '含有违法违规内容',
            })
          }else{
            if(pAcademyNum.length==0){
              wx.showToast({
                title: '请选择学院标签',
                icon:"none"
              })
          }else{
          let publishid = app.globalData.userOpenid+new Date().getTime()
          console.log(publishid)
          let promiseMethod = new Array(that.data.temPicture.length)
          that.data.temPicture.forEach((item,i)=>{
                  promiseMethod[i] = wx.cloud.uploadFile({
                      cloudPath: String(publishid)+i+'.jpg',
                      filePath: that.data.temPicture[i]
                  }).then(res => {
                    publishPicture.push(res.fileID)
                  })
              })
      
          Promise.all([...promiseMethod]).then(() => {
            publishDB.add({  //公告数据库添加一则公告
              data:{
                publishID:publishid,
                promulgatorID:app.globalData.userOpenid, 
                publishBelong:that.data.pColumn, 
                publishAcademy:pAcademyNum, 
                publishLabel:pLabelNum, 
                publishContent:{
                date:util.formatTime(new Date()),
                text:publishText,
                img:publishPicture
                }
              },success:function(res){
                  console.log("添加成功",res)
                   that.successThenSwitch()
                },fail:function(res){
                  console.log("系统出错")
                  wx.showToast({
                    title: '系统出错',
                    icon:"none"
                  })
                }
            })
          })
        }
          }
        }
      })
    }
  },

  //发布成功并跳转
  successThenSwitch:function(){
    let that = this
    wx.showToast({
      title: '发布成功！',
      icon:'none',
      duration:3000
    })
    that.setData({
      showView: (!that.data.showView),
      pAcademy:[],
      pLabel:[],
      // pAcademyNum:[],
      // pLabelNum:[],
      // publishText:'',
      btnSelect:"选择标签",
      temPicture:[],
      // publishPicture:[],
      txtareaValue:''
    })
    pAcademyNum=[]
    publishText=''
    pLabelNum = []
    publishPicture = []
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  //三个栏目选择
  selectSearch:function(){
    let that = this;
    that.setData({
      showView: (!that.data.showView),
      pColumn:1
    })
  },
  selectFind:function(){
    let that = this;
    that.setData({
      showView: (!that.data.showView),
      pColumn:2
    })
  },
  selectExpress:function(){
    let that = this;
    that.setData({
      showView: (!that.data.showView),
      pColumn:3
    })
  },
  //重选栏目
  reSelect:function(){
    let that = this;
    wx.showModal({
      title: '',
      content: '确实重选栏目？\n(将清除页面所有数据)',
      success (res) {
        if (res.confirm) {
          that.setData({
            showView: (!that.data.showView),
            pAcademy:[],
            pLabel:[],
            // pAcademyNum:[],
            // pLabelNum:[],
            // publishText:'',
            btnSelect:"选择标签",
            temPicture:[],
            // publishPicture:[],
            txtareaValue:''
          })
          publishText = ''
          pAcademyNum = []
          pLabelNum = []
          publishPicture = []
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  setReselectBtn:function(){
    this.setData({
      btnSelect:"重选标签"
    })
  },
  previewImage: function (e) {
    app.previewImage(e)
  },
})